package edu.eece261.fall11;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

public class ShoppingLists extends ListActivity {

	public static final String PREFS_NAME = "SHOPPINGLISTLOGIN";

	// Options Menu
	private static final int NEW_LIST = Menu.FIRST;
	private static final int FIND_LIST = Menu.FIRST + 1;
	
	// Context Menu
	private static final int OPEN_LIST = Menu.FIRST;
	private static final int LEAVE_LIST = Menu.FIRST + 1;
	private static final int FINISH_LIST = Menu.FIRST + 2;
	private static final int VIEW_LIST = 0xC0FFEE;

	String selectedTitle;
	String newTitle;
	TextView current;
	
	String finish = "";

	ListDBAdapter listDBA;

	Gson gson;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		listDBA = ListDBAdapter.getListDBAdapter(getApplicationContext());
		listDBA.open();

		gson = new Gson();

		setContentView(R.layout.main);

		fillData();
		
		ListView lv = getListView();
		registerForContextMenu(lv);
		lv.setTextFilterEnabled(true);
		
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
			        int position, long id) {
				Cursor c = listDBA.getEntryMatchingId(id);
				c.moveToFirst();
				startActivityForResult(new Intent(getApplicationContext(),
					ViewList.class).putExtra("list_title", c.getString(ListDBAdapter.TITLE_COLUMN)),
					VIEW_LIST);
			}
		});
	}

	private void fillData() {
		Cursor myStories = listDBA.getAllEntries();
		startManagingCursor(myStories);

		String[] from = new String[] { ListDBAdapter.KEY_TITLE };
		int[] to = new int[] { R.id.shoplistentry };

		SimpleCursorAdapter myStoriesAdapter = new SimpleCursorAdapter(
				getApplicationContext(), R.layout.listrow, myStories, from, to);

		setListAdapter(myStoriesAdapter);
	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, OPEN_LIST, 0, R.string.open_list);
		menu.add(0, LEAVE_LIST, 1, R.string.leave_list);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		Cursor c = listDBA.getEntryMatchingId(info.id);
		c.moveToFirst();
		selectedTitle = c.getString(ListDBAdapter.TITLE_COLUMN);
		switch (item.getItemId()) {
		case OPEN_LIST:
			startActivityForResult(new Intent(getApplicationContext(),
					ViewList.class).putExtra("list_title", selectedTitle),
					VIEW_LIST);
			fillData();
			return true;
		case LEAVE_LIST:
			if (HTTPHelp.getActivityHTTPHelp().leaveList(selectedTitle,
					getApplicationContext())) {
				makeToast("Left list successfully.");
				fillData();
			} else {
				makeToast("Error leaving list.");
			}
			return true;
		case FINISH_LIST:
			if (finish.equals("Finish List")) {
				// HTTPHelp.getActivityHTTPHelp().finishStory()
			}
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, NEW_LIST, 0, R.string.new_list);
		menu.add(0, FIND_LIST, 0, R.string.find_list);
		return result;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case NEW_LIST:
			showDialog(-1);
			return true;
		case FIND_LIST:
			final LinkedList<Messages.ShopList> llResults = HTTPHelp.getActivityHTTPHelp().findLists(0, getApplicationContext());
			ArrayList<String> llTitles = new ArrayList<String>();
			for(int i = 0; i < llResults.size(); i++) {
				llTitles.add(llResults.get(i).getTitle());
			}
			showResults(llTitles, llResults);
		default:
		}

		return super.onOptionsItemSelected(item);
	}
	
	private void showResults(final ArrayList<String> listTitles, final LinkedList<Messages.ShopList> listResults) {
		ListView lvResults = new ListView(this);
		final ArrayAdapter<String> aaLists = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, listTitles);
		lvResults.setAdapter(aaLists);
		this.setTheme(android.R.style.Theme_Black);
		new AlertDialog.Builder(this).setTitle("Search Results").setSingleChoiceItems(aaLists, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				confirmAdd(listResults.get(which), listTitles, listResults);
				dialog.dismiss();
			}
		}).create().show();
		this.setTheme(android.R.style.Theme_Light);
	}
	
	private void confirmAdd(final Messages.ShopList list, final ArrayList<String> listTitles, final LinkedList<Messages.ShopList> listResults) {
		String updated = convertTime(list.getTimestamp());
		final String password = list.getPassword();
		TextView tvData = new TextView(getApplicationContext());
		tvData.setText("Title: " + list.getTitle() + "\nOwner: " + list.getOwner() + "\nItems: " + list.getItems().size() + "\nUpdated: " + updated);
		final EditText etPassword = new EditText(getApplicationContext());
		etPassword.setHint("Password");
		etPassword.setText("");
		LinearLayout llPassword = new LinearLayout(getApplicationContext());
		llPassword.setOrientation(1);
		llPassword.addView(tvData);
		llPassword.addView(etPassword);
		this.setTheme(android.R.style.Theme_Black);
		new AlertDialog.Builder(this).setTitle("Join List?")
		.setView(llPassword)
		.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (etPassword.getText().toString().equals(password) || password.length() == 0)
				{
					if (HTTPHelp.getActivityHTTPHelp().joinList(list.getTitle(), getApplicationContext()))
					{
						dialog.dismiss();
						fillData();
						makeToast("List joined successfully.");
					} else {
						dialog.dismiss();
						makeToast("Error joining list.");
					}
				} else {
					makeToast("Invalid password");
					dialog.dismiss();
				}
				etPassword.setText("");
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				showResults(listTitles, listResults);
				dialog.dismiss();
				etPassword.setText("");
			}
		}).create().show();
		this.setTheme(android.R.style.Theme_Light);
	}
	
	public String convertTime(long timestamp) {
		Calendar time = Calendar.getInstance();
		time.setTimeInMillis(timestamp);
		String month = "";
		switch(time.get(Calendar.MONTH)) {
		case Calendar.JANUARY:
			month = "Jan ";
			break;
		case Calendar.FEBRUARY:
			month = "Feb ";
			break;
		case Calendar.MARCH:
			month = "Mar ";
			break;
		case Calendar.APRIL:
			month = "Apr ";
			break;
		case Calendar.MAY:
			month = "May ";
			break;
		case Calendar.JUNE:
			month = "June ";
			break;
		case Calendar.JULY:
			month = "July ";
			break;
		case Calendar.AUGUST:
			month = "Aug ";
			break;
		case Calendar.SEPTEMBER:
			month = "Sept ";
			break;
		case Calendar.OCTOBER:
			month = "Oct ";
			break;
		case Calendar.NOVEMBER:
			month = "Nov ";
			break;
		case Calendar.DECEMBER:
			month = "Dec ";
		}
		
		String minute = "";
		if (time.get(Calendar.MINUTE) < 10) {
			minute = "0" + time.get(Calendar.MINUTE);
		} else {
			minute = time.get(Calendar.MINUTE) + "";
		}
			
		return month + time.get(Calendar.DAY_OF_MONTH) + ", " + time.get(Calendar.YEAR) + " at " + time.get(Calendar.HOUR) + ":" + minute;
	}

	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		if (id == -1) {
			LinearLayout llNew = new LinearLayout(getApplicationContext());
			final EditText etTitle = new EditText(getApplicationContext());
			final EditText etPassword = new EditText(getApplicationContext());
			etTitle.setText("");
			etPassword.setText("");
			etTitle.setHint("Title");
			etPassword.setHint("Password (Optional)");
			llNew.setOrientation(1);
			llNew.addView(etTitle, 0);
			llNew.addView(etPassword, 1);
			
			builder.setTitle("New Shopping List").setView(llNew).setPositiveButton(
					"Create", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							if (etTitle.getText().toString().equalsIgnoreCase("")) {
								makeToast("Shopping lists must have titles.");
							} else {
								if (HTTPHelp.getActivityHTTPHelp().addList(etTitle.getText().toString(), etPassword.getText().toString(), getApplicationContext())) {
									makeToast("Shopping list created successfully.");
									fillData();
									etTitle.setText("");
									etPassword.setText("");
								} else {
									makeToast("List creation failed.");
									dialog.dismiss();
									etTitle.setText("");
									etPassword.setText("");
								}
							}
						}
					}).setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							etTitle.setText("");
							etPassword.setText("");
							dialog.dismiss();
						}
					});
		}
		
		AlertDialog alert = builder.create();
		return alert;
	}
	
	protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        if (requestCode == VIEW_LIST) {
            fillData();
        }
    }
	
	void makeToast(String alert) {
		Toast.makeText(getApplicationContext(), alert, Toast.LENGTH_SHORT)
				.show();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		startService(new Intent(getApplicationContext(), ShoppingListService.class));
	}
	
	public void onPause() {
		super.onPause();
		stopService(new Intent(getApplicationContext(), ShoppingListService.class));
	}
}